<template>
    <div class="tree-controller">
        
        <el-input
          class="input_css"
          placeholder="此处键入'关键词'搜索查询"
          prefix-icon="el-icon-search"
          v-model="treeFilter"
          size="small"
          clearable
        ></el-input>
        <el-tree
          :data="treeData"
          :props="defaultProps"
          highlight-current
          :check-strictly="false"
          @node-click="handleNodeClick"
          :default-expand-all="false"
          :expand-on-click-node="true"
          :check-on-click-node="false"
          :show-checkbox="true"
          @check="handleCheck"
          ref="treeRef"
          node-key="nodeNo"
          class="tree_css"
          :filter-node-method="filterNode"
          
        >
        <template #default="{ node }">
            <el-tooltip
                class="box-item"
                effect="dark"
                :content="node.label"
                placement="top-start"
            >
                <span class="custom-tree-node-label common-text-ellipsis"> {{ node.label }}</span>
            </el-tooltip>
        </template>
        </el-tree>
    </div>
  </template>
  <script lang="ts" setup>
  import { reactive, onMounted, ref, watch,toRaw,defineEmits,defineProps } from 'vue'
  import { apiGetFullModuleTreeForMaint } from '@/api/user'
  import { ElTree } from 'element-plus'
  import { Search } from '@element-plus/icons-vue'
  import { useMessage } from '@/hooks/message'
  const props = defineProps({
    treeOptType:{
        type:Number,
        default:0
    },
    copyAuth:{
        type:Array,
        default:()=>[]
    },
    drawer:{
        type:Boolean,
        default:true
    },
    //权限管理，只有按钮和页面可以勾选
    buttonPage_Ckeck:{
        type:Boolean,
        default:false
    }
  })
  const treeData = ref([])
  const checkedNodes = ref([])
  const treeFilter = ref('');
  const treeRef = ref<InstanceType<typeof ElTree>>()
  const emits = defineEmits(['select-node','select-single-data','close-drawer'])
  const defaultProps = {
    children:'subNodes',
    label: (data) => !data.payload.resourceType ? `[${data.payload.nodeEname}]  ${data.payload.nodeCname}` : data.payload.nodeCname,
    // disabled:(val,node)=> {
    //     if(props.buttonPage_Ckeck){
    //         if(!node.data.payload.resourceId ) return true
    //     }
        
    // }
  }
    const handleNodeClick = (data, node, component) => {
        emits('select-single-data',data)
    };
    const filterNode = (value: string, data: Tree) => {
        if (!value) return true
        return data.payload.nodeCname.includes(value)
    }

  const getMenuList = () =>{
    apiGetFullModuleTreeForMaint()
      .then((res) => {
        if (res.data.success) {
            treeData.value = res.data.data.subNodes
            // emits('get-tree-data',treeData.value)
        }
      })
      .catch((error: any) => {
        // 处理错误
      })
  }
  const handleCheck = () => {
        let arr = treeRef.value.getCheckedNodes();
        emits('select-node',arr)
      };
    const optFunction = (val) =>{
        if(val == 1){
            treeRef.value?.setCheckedKeys(treeData.value.map(item => item.nodeNo))  
            console.log(treeRef.value.getCheckedNodes(),'查看数据666') 

        }else if(val == 2){
            treeRef.value?.setCheckedKeys([],false);
            console.log(treeRef.value.getCheckedNodes(),'取消数据666') 
        }else if(val == 3){//折叠
            Object.values(treeRef.value.store.nodesMap).forEach(node => node.collapse(true))

        }else if(val == 4){//展开
            Object.values(treeRef.value.store.nodesMap).forEach(node => node.expand(true))
        }
    }
    const getLeafNodes = (tree) =>{
        const leafNodes = []

        function recurse(node) {
            if (!node.subNodes || node.subNodes.length === 0) {
            leafNodes.push(node)
            } else {
                node.subNodes.forEach((childNode) => recurse(childNode))
            }
        }

        tree.forEach((node) => recurse(node))
        return leafNodes
    }
    const leafNodes = ref([])
    const logLeafNodes = () => {
        leafNodes.value = getLeafNodes(treeData.value)
    }
    const copyVal = ref([])
    const copyTreeFunction = (data) =>{
        logLeafNodes()
        leafNodes.value.forEach(item1 => {
            props.copyAuth.forEach(item2 => {
                if(item1.payloadId == item2.resourceId){
                    copyVal.value.push(item1)
                }
            });
        });
        emits('close-drawer',copyVal.value) 
    }
    watch(treeFilter, (val) => {
        treeRef.value!.filter(val)
    })
    watch(() => props.treeOptType, (newVal) => {
        optFunction(newVal)
    });
    watch(() => props.copyAuth, (newVal) => {
        copyTreeFunction(newVal)
    });
    watch(() => props.drawer, (newVal) => {
        let arr = copyVal.value.map((v)=>{
            return v.nodeNo
        })
        if(newVal == false && copyVal.value.length) treeRef.value?.setCheckedKeys(arr)
    });
  
  onMounted(() => {
    let arr = props.copyAuth.map((v)=>{
        return v.resourceId
    })
    treeRef.value?.setCheckedKeys(arr)
    getMenuList()
  })
  </script>
  <style lang="less" scoped>
  .tree-controller{
    h3{
        border-bottom:1px solid #eee;
        line-height: 50px;
        padding-left:20px;
    }
    .input_css{
        padding: 0px 10px;
        height:30px;
        line-height: 30px;
        
    }
    .tree_css{
        // width:220px;
        margin: 20px 10px;
    }
  }
  ::v-deep(.el-dropdown-menu__item) {
    padding: 5px 16px;
    border-radius: 2px;
    margin: 4px;
  }
  </style>
  